package com.grades.springboot.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.grades.springboot.entity.Result;
import com.grades.springboot.entity.Validation;
import com.grades.springboot.mapper.ValidationMapper;
import com.grades.springboot.service.ValidationService;
import com.grades.springboot.util.Encrypt;
import com.grades.springboot.util.SendMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;


@Service
public class ValidationServiceImpl implements ValidationService {

    @Autowired
    private ValidationMapper validationMapper;

    @Override
    public Result<?> sendValidation(String email) {
        int count = validationMapper.getCount(email);
        if (count > 0) {
            validationMapper.deleteValidation(email);
        }
        sendEmail(email);
        return Result.success();
    }

    @Override
    public void sendEmail(String email) {
        String code = RandomUtil.randomNumbers(4);
        String msg = "尊敬的用户，您的验证码是：" + code + "。可用于验证您的邮箱。请妥善保管，打死都不要告诉别人。";
        SendMail.Mail_Code(email, "【邮箱验证】", msg);
        //将验证码存入数据库中
        saveCode(email, code, DateUtil.offsetMinute(new Date(), 5));
    }

    @Override
    public void saveCode(String email, String code, DateTime time) {
        validationMapper.saveCode(email, Encrypt.toMD5(code),time);
    }

//    @Override
//    public int findValidation(String email) {
//        return validationMapper.findValidation(email);
//    }

    @Override
    public boolean checkValidation(String email, String code) {
//        System.out.println("======email:" + email);
        Validation v = validationMapper.findValidation(email);
        String validation = v.getCode();
        Timestamp time = v.getTime();
        return validation.equals(code) && time.after(new Date());
    }

//    @Override
//    public void deleteValidation(String email) {
//        validationMapper.deleteValidation(email);
//    }
}
